<?php
// $employee here is used as a synonym for $user
require_once "../lib/common.php";
$response = array();


if ( isset($_POST['register'])) {
    if ( ! isset($_POST['password']) || strlen($_POST['password']) < 5 ) {
        error_die("password must be at least 5 characters long");
    } else {
        $_POST['password'] = md5($_POST['password']);
    }
    $employee = new User();
    $ret = $employee->update_attributes_filter($_POST,
        array("name"=>1,"email"=>1,"password"=>1));
    if ($ret == false) {
        $err_msgs = $employee->errors->full_messages();
        error_die($err_msgs[0]);
    }
} else {
    if (Login::getLoggedIn() == null) {
        error_die("access denied");
    }
    if (Login::getLoggedIn()->admin != 1) {
        error_die("access denied");
    }
    if (isset($_POST['password'])) {
        $_POST['password'] = md5($_POST['password']);
    }
    if ( isset($_POST['update']) ) {
        if ( isset($_POST['id']) && !empty($_POST['id']) ) {
            $employee = User::find($_POST['id']);
            $ret = $employee->update_attributes_filter($_POST,$employee->attributes());
            if ($ret == false) {
                $err_msgs = $employee->errors->full_messages();
                error_die($err_msgs[0]);
            }
        } else {
            $employee = new User();
            $ret = $employee->update_attributes_filter($_POST,$employee->attributes());
            if ($ret == false) {
                $err_msgs = $employee->errors->full_messages();
                error_die($err_msgs[0]);
            }
        }
    } elseif ( isset($_POST['delete']) ) {
        $user = User::find($_POST['id']);
        if ($user->reviews != null) {
            foreach ($user->reviews as $review) {
                $review->user_id = 0;
                $review->save();
            }
        }
        if ($user->carts != null) {
            foreach ($user->carts as $item) {
                $item->delete();
            }
        }
        $user->delete();
    } else {
        $empty_employee = new User();
        $response['attributes'] = array_keys($empty_employee->attributes());
        unset($empty_employee);
        $employees_attributes = array();
        foreach (User::all() as $employee) {
            array_push($employees_attributes,$employee->attributes_but(array("password")));
        }
        $response['collection'] = $employees_attributes;
    }
}

if (!empty($response)) {
    echo json_encode($response);
}
?>
